import React,{useRef,useEffect,useState, useCallback} from 'react';
import ProTable from '@ant-design/pro-table';
import { getClassInfo,saveMemberSigned } from './service';
import { Button,message,Select } from 'antd';
import { CheckOutlined } from '@ant-design/icons';
import moment from 'moment'
import {HasPermission} from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const SignTable = props =>{
  const actionRef = useRef();
  const [columns, setColumns] = useState([
    {
        title: '课程',
        dataIndex: 'courseName',
        hideInSearch:true
      },
      {
        title: '开课时间',
        dataIndex: 'courseDate',
      },
      {
        title: '售价',
        dataIndex: 'coursePrice',
        hideInSearch:true
      },
      {
        title: '预约人数',
        dataIndex: 'bookingNum',
        hideInSearch:true
      },  
      {
        title: '课程类型',
        dataIndex: 'courseType',
        valueEnum: {
          1: {
            text: '大班课',
            status: 'Success',
          },
          2: {
            text: '小班课',
            status: 'Success',
          },
          3: {
            text: '私教课',
            status: 'Error',
          },
        },
      },
      {
          title: '操作',
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => {
              if(props.signStatus=='1'){
                  return <AuthButton auth={[`sign:sign:sign`]} type="link"  onClick={() => _saveMemberSigned(record)}>签到</AuthButton>
              }
          }
      }, 
  ])
  useEffect(() => {
    //遍历了两次
    actionRef.current.reload();
    if(!(columns.length==7)){
        columns.push(
            {
              title: '课程',
              dataIndex: 'courseId',
              hideInTable:true,
              renderFormItem:()=><Select placeholder="请选择"  style={{width:'100%'}} showSearch  optionFilterProp="children"  filterOption={(input, option) =>
                option.children.indexOf(input) >= 0
              }>
                 {
                    props.courseList&&props.courseList.map((item,index)=> <Select.Option value={item.id} key={index}>{item.courseName}</Select.Option>)
                  }
              </Select>
            })
        setColumns(columns)
    }
   }, [props.memberId,props.signStatus]);

  const batchSign = useCallback(async(selectedRows)=>{
    const hide = message.loading('正在批量签到');
    if (!selectedRows) return true;
    try {
      let result = await saveMemberSigned({
        bookingCourseId:selectedRows.map(row => row.bookingCourseId),
        memberId:props.memberId
      });
      hide();
      if(result.code ==0){
        message.success('批量签到成功，即将刷新');
        actionRef.current.reload()
        return true;
      }else{
        message.error(result.message);
        return false; 
      }
    } catch (error) {
        console.log(error)
      hide();
      message.error('批量签到失败，请重试');
      return false;
    }
  },[props.memberId])
  const _saveMemberSigned = useCallback(async(record)=>{
    const hide = message.loading('正在签到');
    try {
      let result = await saveMemberSigned({
        bookingCourseId:[record.bookingCourseId],
        memberId:record.memberId
      });
      hide();
      if(result.code ==0){
        message.success('签到成功，即将刷新');
        actionRef.current.reload()
        return true;
      }else{
        message.error(result.message);
        return false; 
      }
    } catch (error) {
      console.log(error)
      hide();
      message.error('签到失败，请重试');
      return false;
    }
  },[props.memberId])
    return  <ProTable
    actionRef={actionRef}
    rowKey="bookingCourseId"
    toolBarRender={(action, { selectedRows }) => {
      if(props.activeKey === 1){
        return [
          <AuthButton auth={[`sign:sign:batch:sign`]} type="primary" icon={<CheckOutlined />}  onClick={() => batchSign(selectedRows)}>批量签到</AuthButton>
        ]

      } 
    }}
    tableAlertRender={({selectedRowKeys, selectedRows}) => (
      <div>
        已选择{' '}
        <a
          style={{
            fontWeight: 600,
          }}
        >
          {selectedRowKeys.length}
        </a>{' '}
        项
      </div>
    )}
    request={params => {
      let _params={
        memberId:props.memberId,
        signStatus:props.signStatus,
        ...params,
      }
      if(params.courseDate){
          if(params.courseDate[0]){
                _params.startDate = moment(params.courseDate[0]).format('YYYY-MM-DD')
          }
          if(params.courseDate[1]){
            _params.endDate = moment(params.courseDate[1]).format('YYYY-MM-DD')
      }
      }
      delete _params.courseDate
      delete _params.current
      delete _params.pageSize
      return getClassInfo(_params)
    }}
    columns={columns}
    rowSelection={{}}
  />
}
export default SignTable; 